package com.djl.hw02client.service;


import com.djl.hw02client.domain.XmlUser;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@Service
public class UserService {

    RestTemplate rest = new RestTemplate();



    public List<XmlUser> queryAll(){
        String url ="http://localhost:8099/user/queryAll";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Object> objectHttpEntity = new HttpEntity<>(headers);
        ParameterizedTypeReference<List<XmlUser>> listParameterizedTypeReference = new ParameterizedTypeReference<List<XmlUser>>(){};
        ResponseEntity<List<XmlUser>> exchange = rest.exchange(url, HttpMethod.POST, objectHttpEntity, listParameterizedTypeReference);
        return exchange.getBody();
    }

    public List<XmlUser> queryAllXml() {
        String url ="http://localhost:8099/user/queryAll";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_XML);
        HttpEntity<Object> objectHttpEntity = new HttpEntity<>(headers);
        ParameterizedTypeReference<List<XmlUser>> listParameterizedTypeReference = new ParameterizedTypeReference<List<XmlUser>>(){};
        ResponseEntity<List<XmlUser>> exchange = rest.exchange(url, HttpMethod.POST, objectHttpEntity, listParameterizedTypeReference);
        return exchange.getBody();
    }

    public XmlUser queryById(int id){
        String url ="http://localhost:8099/user/queryById/"+id;
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Object> objectHttpEntity = new HttpEntity<>(headers);
        ResponseEntity<XmlUser> forEntity = rest.getForEntity(url, XmlUser.class, objectHttpEntity);
        return forEntity.getBody();
    }

    public XmlUser queryByIdXml(int id) {
        String url ="http://localhost:8099/user/queryById/"+id;
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_XML);
        HttpEntity<Object> objectHttpEntity = new HttpEntity<>(headers);
        ResponseEntity<XmlUser> forEntity = rest.getForEntity(url, XmlUser.class, objectHttpEntity);
        return forEntity.getBody();
    }
}
